<template>
  <div v-loading="loading" class="course-config-wrapper">
    <div class="el-row--flex is-justify-space-between" style="height: calc(100% - 50px);overflow: hidden">
      <div class="left-course-wrapper">
        <div class="topTitle">素材</div>
        <!--        <div class="tabs">
                  <div :class="currIndex === 0 ? 'active' : ''" @click="tabClick(0)">素材</div>
                  <div :class="currIndex === 1 ? 'active' : ''" @click="tabClick(1)">图片</div>
                </div>-->
        <div class="right_action_wrapper">
          <div class="course-wrapper-con">
            <div class="bigBtn">截屏工具</div>
            <div class="picBtns">
              <div>本地导入</div>
              <div @click="selectImg(2)">图库选择</div>
            </div>

            <div class="imgList">
              <div class="imgItem" v-for="(item,index) in imgList" :key="index"
                   :class="imgIndex === index && !isSort ? 'active' : ''">
                <img :src="imgUrlPrefix + item.contentUrl" alt="" @dblclick="imgClick(index)">
                <div class="bottomName el-row--flex is-justify-space-between">
                  <div class="img_name">{{ item.contentName }}</div>
                  <div v-if="!isSort" class="optBtn">
                    <span @click="replaceImg(index)"><img src="@/assets/images/change.svg" alt="">替换</span>
                    <span @click="delImg(index)"><img src="@/assets/images/del.svg" alt="">删除</span>
                  </div>
                </div>

                <div class="upDownBtn" v-if="isSort">
                  <img src="@/assets/images/up.png" :class="index === 0?'disabled':''" alt="上移"
                       @click="moveUp(index)">
                  <img src="@/assets/images/down.png" alt="下移" :class="index === imgList.length - 1 ?'disabled':''"
                       @click="moveDown(index)">
                </div>
                <div v-if="!isSort" style="border-top: 1px solid #DCDFE6;padding: 5px 20px">
                  <el-radio :value="item.pageOrderType" @input="updatePageOrderType(index, 1)" :label="1">设为开始节点
                  </el-radio>
                  <el-radio :value="item.pageOrderType" @input="updatePageOrderType(index, 2)" :label="2">设为结果节点
                  </el-radio>
                </div>

              </div>
              <div v-show="imgList.length" class="smallBtn" @click="sort" style="float: right">
                <img :src="isSort ? require('@/assets/images/save.png'):require('@/assets/images/paixu.png')"
                     alt="">{{ isSort ? '保存' : '排序' }}
              </div>
            </div>
          </div>
          <div class="toolbox_wrapper" :style="{
            height: toolboxCollapse ? '40px' : '271px',
          }">
            <div class="el-row--flex is-justify-space-between topTitle" style="border-top: 1px solid #DCDFE6; ">
              <span>工具</span>
              <i :class="{
                'el-icon-arrow-down': !toolboxCollapse,
                'el-icon-arrow-up': toolboxCollapse,
              }" @click="toolboxCollapse = !toolboxCollapse"/>
            </div>
            <div class="toolBox">
              <div class="toolItems">
                <div @click="markMode = 1"><img src="@/assets/images/icon01.png" alt="锚点区域">
                  <div>锚点区域</div>
                </div>
                <div @click="markMode = 2"><img src="@/assets/images/icon02.svg" alt="帮助指引">
                  <div>帮助指引</div>
                </div>
                <div @click="markMode = 3"><img src="@/assets/images/icon03.svg" alt="滚动条">
                  <div>滚动条</div>
                </div>
                <div @click="markMode = 4"><img src="@/assets/images/icon04.svg" alt="遮盖区域">
                  <div>遮盖区域</div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="right-course-wrapper" style="overflow:scroll;">
        <div class="imgbox" id="imgbox" ref="at">
          <ui-marker
              v-if="currentImage"
              ref="aiPanel-editor"
              class="ai-observer"
              v-bind:uniqueKey="uuid"
              :ratio="0"
              @vmarker:onAnnoSelected="onAnnoSelected"
              @vmarker:onUpdated="onUpdated"
              @vmarker:onImageLoad="onImageLoad"
              @vmarker:onAnnoRemoved="onAnnoRemoved"
              @vmarker:onAnnoAdded="onAnnoAdded"
              v-bind:readOnly="readOnly"
              v-bind:imgUrl="imgUrlPrefix + currentImage"
          >
          </ui-marker>
        </div>

        <div v-for="(itemParent,indexParent) in markDataList" :key="indexParent"
             :style="{position:'absolute',left: itemParent.tranLeft, top: itemParent.tranTop}">
          <div v-if="itemParent.elementType < 4" class="addMark">
            <div class="formList">
              <el-input :value="itemParent.elementDesc"
                        @input="(val) => updateDeepFormData(markDataList, indexParent, 'elementDesc', val)"
                        :type="itemParent.elementType === 2 ? 'textarea' : undefined"
                        :disabled="readOnly"
                        size="mini"
                        :placeholder="itemParent.elementType === 2 ? '请输入帮助指引内容' : '请输入按钮名称'"></el-input>
            </div>
            <div v-if="itemParent.elementType !== 2">
              <div class="formList">
                <el-select :value="itemParent.sendPageId"
                           @input="(val) => updateDeepFormData(markDataList, indexParent, 'sendPageId', val)"
                           :disabled="readOnly"
                           size="mini"
                           allow-create filterable default-first-optionsize="small" style="width:100%"
                           placeholder="请选择需要链接的页面">
                  <el-option
                      v-for="(item,index) in imgList.filter((it,index) => index !== imgIndex)"
                      :key="index"
                      :label="item.contentName"
                      :value="item.pageId">
                  </el-option>
                </el-select>
              </div>

            </div>
            <div style="color: #ffffff;text-align: right">
              <el-select v-if="itemParent.elementType === 3 || itemParent.elementType === 1"
                         :value="itemParent.isStandardFlow"
                         size="mini"
                         @input="(v) => updateDeepFormData(markDataList, indexParent, 'isStandardFlow', v)"
                         :disabled="readOnly"
                         placeholder="请选择" style="width: 100%">
                <el-option label="标准流程" value="1"></el-option>
                <el-option label="非标准流程" value="0"></el-option>
              </el-select>
              <p v-if="itemParent.elementType === 2 || itemParent.isStandardFlow === '1' ">
                第
                <el-input-number :value="itemParent.elementOrder"
                                 @input="(val) => updateDeepFormData(markDataList, indexParent, 'elementOrder', val)"
                                 :disabled="readOnly"
                                 size="mini"
                                 style="width: 85px"
                                 controls-position="right" :min="1" :max="1000"></el-input-number>
                步
              </p>
            </div>
          </div>

        </div>

      </div>
    </div>


    <div class="el-row--flex is-justify-space-between bottom-wrapper">
      <el-button type="primary" @click="toImage" :disabled="isSort || imgList.length === 0">保存，去确认考核点
      </el-button>
      <el-button type="primary" plain @click="toPreview" :disabled="isSort || imgList.length === 0">预览</el-button>
    </div>

    <el-dialog :title="picType === 1 ? '本地导入' : '选择图片'" :visible.sync="chooseImg" width="50%">
      <div class="el-row--flex formList">
        <div class="nameItem">AI题库</div>
        <div class="bordered">{{ galleryData.testName }}</div>
      </div>
      <div class="el-row--flex formList">
        <div class="nameItem">题库分类</div>
        <div class="bordered">{{ galleryData.catalogueName }}</div>
      </div>
      <div class="el-row--flex formList">
        <div class="nameItem">实操课题</div>
        <div class="bordered">{{ galleryData.bdQuestionName }}</div>
      </div>
      <div class="el-row--flex formList" v-if="picType === 2">
        <div class="nameItem">图片选择</div>
        <div class="el-row--flex">
          <div v-for="(item) in galleryData.page || []" class="picList" :key="item.pageId"
               @click="selectGalleryImg(item)">
            <el-image style="width: 100px; height: 100px" :src="imgUrlPrefix + item.contentUrl" fit="cover"></el-image>
            <img
                :src="selectedList.indexOf(item.pageId) > -1 ? require('@/assets/images/choose.png') : require('@/assets/images/noChoose.png')"
                alt="">
            <div class="img_name">{{ item.contentName }}</div>
          </div>
        </div>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="chooseImg = false">取消</el-button>
        <el-button type="primary" @click="gallerySelectedConfirm">确定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>

import {AIMarker} from "vue-picture-bd-marker";
import {
  courseImgDelete,
  courseReplace,
  queryCourseImgList,
  queryGallery,
  savePageConfig,
  selectPageConfig,
  ssoLogin,
  updateCourseNode,
  updateCoursePicture,
  updatePageOrder
} from "@/api";
import {decryptAES} from "@/utils/crypto";

export default {
  name: "CourseConfig",
  components: {"ui-marker": AIMarker},
  data() {
    return {
      imgUrlPrefix: process.env.VUE_APP_ASSETS_URL,
      toolboxCollapse: false,
      loading: false,
      currIndex: 1,
      isSort: false,
      chooseImg: false,
      picType: 1,
      galleryData: {},
      selectedList: [],
      imgIndex: -1,
      imgList: [],
      markDataList: [],
      uuid: '',
      /**
       * 1: 锚点区域；2：帮助指引；3：滚动条；4：遮盖区域
       */
      markMode: 0,
      total: 0,
      imageInfo: [],
      importMode: 'append'
    };
  },
  computed: {
    readOnly() {
      return this.markMode === 0 || this.isSort
    },
    currentImage() {
      if (this.imgList.length === 0 || this.imgIndex < 0) return ''
      if (this.isSort) {
        return this.imgList.find(item => item.pageId === this.sortCurrentPageIdTemp).contentUrl
      }
      return this.imgList[this.imgIndex].contentUrl
    },
  },
  created() {
    this.initData()
  },
  mounted() {
    this.handleResize = () => {
      this.onUpdated(this.markDataList, '')
    }
    window.addEventListener('resize', this.handleResize)
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize)
  },
  methods: {
    /**
     * 更新节点是开始节点或者结果节点
     * @param index 节点索引
     * @param type 1：起始，2：结果
     */
    updatePageOrderType(index, type) {
      const oldTypeIndex = this.imgList.findIndex(item => item.pageOrderType === type)
      if (oldTypeIndex > -1) {
        this.updateDeepFormData(this.imgList, oldTypeIndex, 'pageOrderType', 0)
      }
      this.updateDeepFormData(this.imgList, index, 'pageOrderType', type)
      updateCourseNode(this.imgList[index].questionId, this.imgList[index].pageId, type).catch(() => {
        this.updateDeepFormData(this.imgList, index, 'pageOrderType', 0)
        if (oldTypeIndex > -1) {
          this.updateDeepFormData(this.imgList, oldTypeIndex, 'pageOrderType', type)
        }
      })
    },
    /**
     * 更新深层数据
     * @param dataList 原数组
     * @param index 索引
     * @param field 数组内对象的字段名
     * @param value 值
     */
    updateDeepFormData(dataList, index, field, value) {
      dataList[index][field] = value
      this.$set(dataList, index, dataList[index])
    },
    /**
     * 图片导入确认
     * @return {Promise<void>}
     */
    async gallerySelectedConfirm() {
      if (!this.selectedList.length) {
        this.$message({
          message: '请选择图片',
          type: "error",
        });
        return
      }
      const page = []
      this.galleryData.page.forEach(item => {
        if (this.selectedList.indexOf(item.pageId) > -1) {
          page.push(item)
        }
      })
      if (this.importMode === "replace") {
        try {
          await courseReplace(page[0].questionId, this.imgList[this.replaceImgIndex].pageId, page[0].pageId)
          delete this.markCache[this.imgList[this.replaceImgIndex].pageId]
          this.chooseImg = false
          this.imgList.splice(this.replaceImgIndex, 1, ...page)
          this.markDataList = []
          this.$refs['aiPanel-editor'].getMarker().clearData()
        } catch (e) {
          console.log("图片替换失败")
        }
        return
      }
      try {
        await updateCoursePicture(page[0].questionId, page.map(item => ({pageId: item.pageId})))
        this.$message({
          message: '操作成功',
          type: "success",
        });
        this.chooseImg = false
        this.imgList.push(...page)
        if (this.imgList.length === page.length) {
          this.imgClick(0)
        }
      } catch (e) {
        console.log("图片导入失败")
      }
    },
    initData() {
      this.loading = true;
      const token = this.$route.query.token
      if (!token) {
        console.error("没有获取到token参数")
        this.$router.push('/error')
        return
      }
      let queryData
      try {
        queryData = JSON.parse(decryptAES(decodeURIComponent(token)))
      } catch (e) {
        console.error(e)
        this.$router.push('/error')
        return
      }
      console.log(queryData)
      const date = new Date()
      let ssoLoginTimeStr = `${date.getFullYear()}`
      ssoLoginTimeStr += date.getMonth() > 8 ? `${date.getMonth() + 1}` : `0${date.getMonth() + 1}`
      ssoLoginTimeStr += date.getDate() > 9 ? `${date.getDate()}` : `0${date.getDate()}`
      ssoLoginTimeStr += date.getHours() > 9 ? `${date.getHours()}` : `0${date.getHours()}`
      ssoLoginTimeStr += date.getMinutes() > 9 ? `${date.getMinutes()}` : `0${date.getMinutes()}`
      ssoLoginTimeStr += date.getSeconds() > 9 ? `${date.getSeconds()}` : `0${date.getSeconds()}`

      const data = {
        // "agentId": queryData.agentId,
        "agentId": "83b605dd5ad24ba6940a9b8956aa65e8",
        "user": queryData.userName,
        // "bdQuestionId": queryData.questionId,
        "bdQuestionId": "6c823ef0-455b-4aaa-8287-ce5859c77495",
        ssoLoginTimeStr
      }
      ssoLogin(data).then(res => {
        this.currentUserUnique = res.currentUserUnique
        return queryCourseImgList(this.currentUserUnique)
      }).then(res => {
        this.imgList = res
        if (this.imgList.length) {
          this.imgClick(0)
        }
      }).catch(() => {
        console.log("初始载入数据失败")
      }).finally(() => {
        this.loading = false;
      })

    },
    async selectImg(type, mode = "append") {
      if (this.isSort) {
        return
      }
      this.importMode = mode
      this.selectedList = []
      this.galleryData = {}
      if (type === 2) {
        try {
          this.galleryData = await queryGallery(this.currentUserUnique)
          console.log(this.galleryData)
        } catch (e) {
          return
        }
      }
      this.chooseImg = true;
      this.picType = type;
    },
// 图片选择
    selectGalleryImg(item) {
      if (this.importMode === "replace") {
        this.selectedList = [item.pageId]
        return
      }
      if (this.selectedList.length >= 10) {
        this.$message({
          message: '最多支持勾选10张图片！',
          type: "error",
        });
        return
      }
      const index = this.selectedList.indexOf(item.pageId)
      if (index > -1) {
        this.selectedList.splice(index, 1)
      } else {
        this.selectedList.push(item.pageId)
      }

    },
    async sort() {
      this.isSort = !this.isSort;
      if (this.isSort) {
        this.sortCurrentPageIdTemp = this.imgList[this.imgIndex].pageId
        this.oldOrder = this.imgList.map(item => item.pageId).join()
      } else {
        if (this.oldOrder === this.imgList.map(item => item.pageId).join()) {
          console.log("1")
          return
        }
        console.log("2")
        this.imgIndex = this.imgList.findIndex(item => item.pageId === this.sortCurrentPageIdTemp)
        this.sortCurrentPageIdTemp = undefined
        const page = this.imgList.map((item, index) => {
          return {
            pageId: item.pageId,
            pageOrder: index + 1
          }
        })
        updatePageOrder({
          questionId: this.imgList[this.imgIndex].questionId,
          page
        }).catch(() => {
        })
      }


    },
    // 上移
    moveUp(index) {
      if (index !== 0) {
        let arr = this.imgList
        arr.splice(index - 1, 1, ...arr.splice(index, 1, arr[index - 1]))
      }
    },
    // 下移
    moveDown(index) {
      let arr = this.imgList
      if (index !== arr.length - 1) {
        arr.splice(index, 1, ...arr.splice(index + 1, 1, arr[index]))
      }
    },
    replaceImg(index) {
      this.replaceImgIndex = index
      this.selectImg(2, "replace")
    },
    delImg(index) {
      this.$confirm('确定删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return courseImgDelete(this.imgList[index].questionId, this.imgList[index].pageId)
      }).then(() => {
        delete this.markCache[this.imgList[index].pageId]
        if (this.imgIndex === index) {
          this.markDataList = []
          this.$refs['aiPanel-editor'].getMarker().clearData()
        }
        this.imgList.splice(index, 1);
        if (this.imgList.length === 0) {
          this.imgList = 0
        } else if (index > 0) {
          this.imgClick(index - 1)
        } else {
          this.imgClick(0)
        }
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
      }).catch((e) => {
        console.error(e)
      });
    },
    async imgClick(index) {
      if (this.isSort) return false
      this.markCache = this.markCache || {};
      const oldElement = this.imgIndex > -1 ? this.markCache[this.imgList[this.imgIndex].pageId] : undefined
      if (this.markDataList.length || oldElement) {
        //判断帮助指引步骤是否连续且从1开始，区间为[1,markDataList.length]
        /*const helpMarkOrderSort = this.markDataList
            .filter(item => item.elementType === 2)
            .map(item => item.elementOrder)
            .sort((a, b) => a - b)
        if (helpMarkOrderSort.length) {
          if (helpMarkOrderSort[0] !== 1
              || helpMarkOrderSort[helpMarkOrderSort.length - 1] !== helpMarkOrderSort.length
              || helpMarkOrderSort.reduce((prev, curr) => prev + curr, 0) !== helpMarkOrderSort.length * (helpMarkOrderSort.length + 1) / 2
          ) {
            this.$message({
              message: '帮助指引步骤必须连续且从1开始',
              type: "error",
            });
            return
          }
        }*/
        for (let item of this.markDataList) {
          if (item.elementType === 1 || item.elementType === 3) {
            if (item.elementDesc === undefined || item.elementDesc.trim() === '') {
              this.$message({
                message: '按钮名称不能为空',
                type: "error",
              });
              return false
            }
            if (item.sendPageId === undefined) {
              this.$message({
                message: '链接页面不能为空',
                type: "error",
              });
              return false
            }
          }
          if (item.elementType === 2) {
            if (item.elementDesc === undefined || item.elementDesc.trim() === '') {
              this.$message({
                message: '帮助指引的内容不能为空',
                type: "error",
              });
              return false
            }
          }
        }
        //判断帮助指引是否只有一个
        if (this.markDataList.filter(item => item.elementType === 2).length > 1) {
          this.$message({
            message: '帮助指引最多只能有一个',
            type: "error",
          });
          return false
        }
        const data = {
          pageId: this.imgList[this.imgIndex].pageId,
          questionId: this.imgList[this.imgIndex].questionId,
          element: this.markDataList.map(item => {
            return {
              x: item.position.x,
              x1: item.position.x1,
              y: item.position.y,
              y1: item.position.y1,
              elementType: item.elementType,
              elementDesc: item.elementDesc,
              elementOrder: item.elementOrder,
              isStandardFlow: item.isStandardFlow,
              sendPageId: item.sendPageId,
            }
          })
        }
        //用于检测是否有数据更新
        let needUpdate = true
        if (oldElement && oldElement.length === data.element.length &&
            oldElement.find((item, index) =>
                item.position.x !== data.element[index].x
                || item.position.x1 !== data.element[index].x1
                || item.position.y !== data.element[index].y
                || item.position.y1 !== data.element[index].y1
                || item.elementType !== data.element[index].elementType
                || item.elementDesc !== data.element[index].elementDesc
                || !Object.is(item.elementOrder, data.element[index].elementOrder)
                || item.isStandardFlow !== data.element[index].isStandardFlow
                || !Object.is(item.sendPageId, data.element[index].sendPageId)) === undefined
        ) {
          needUpdate = false
        }

        if (needUpdate) {
          try {
            await savePageConfig(data)
          } catch (e) {
            return false
          }
          //切换图片焦点是保存数据
          this.markCache[this.imgList[this.imgIndex].pageId] = this.markDataList
        }
        if (index !== this.imgIndex) {
          this.markDataList = []
        }
      }
      if (index === this.imgIndex) {
        return true
      }
      this.markDataList = []
      if (this.markCache[this.imgList[index].pageId]) {
        this.markDataList = this.markCache[this.imgList[index].pageId]
      } else {
        try {
          const res = await selectPageConfig(this.imgList[index].questionId, this.imgList[index].pageId)
          const data = res.map((item) => {
            return {
              tag: '',
              tagName: '',
              elementType: item.elementType,
              position: {
                x: item.x,
                x1: item.x1,
                y: item.y,
                y1: item.y1
              },
              elementDesc: item.elementDesc,
              elementOrder: item.elementOrder,
              isStandardFlow: item.isStandardFlow,
              sendPageId: Number.parseInt(item.sendPageId)
            }
          })
          this.markCache[this.imgList[index].pageId] = data
          this.markDataList = data
        } catch (e) {
          return false
        }
      }
      if (this.imgIndex > -1 && this.imgList[this.imgIndex].contentUrl === this.imgList[index].contentUrl) {
        this.onImageLoad(this.imageInfo)
      }
      this.imgIndex = index;
      return true
    },
    /**记录图片当前的大小和原始大小 data={rawW,rawH,currentW,currentH} */
    //图片加载完成后回调
    onImageLoad(data) {
      console.log("onImageLoad", data)
      this.markClearing = true
      this.$refs['aiPanel-editor'].getMarker().clearData()
      this.$nextTick(() => {
        console.log("开始绘制数据", this.markDataList)
        this.$refs['aiPanel-editor'].getMarker().renderData(this.markDataList)
      })
      this.imageInfo = data
      this.markMode = 1
    },
    // 圈选一个矩形回调
    onAnnoAdded(e) {
      console.log('onAnnoAdded', "添加选框", e);
      this.uuid = e.uuid
      this.$refs[`aiPanel-editor`].getMarker().setTag({
        tagName: '',
        tag: ''
      })
      this.markDataList.forEach((item, index) => {
        if (e.uuid === item.uuid) {
          if (item.elementType === undefined || item.elementType === null) {
            item.elementType = this.markMode
          }
          const markBox = document.getElementById('imgbox')
          const markers = markBox.querySelectorAll('.annotation')
          if (item.elementType === 4) {
            markers[index].style.backgroundColor = 'rgba(0, 0, 0, 0.25)'
            markers[index].style.backdropFilter = 'blur(5px)'
          } else if (item.elementType === 3 || item.elementType === 1) {
            if (item.isStandardFlow === undefined || item.isStandardFlow === null) {
              item.isStandardFlow = '1'
              const currModeMarkData = this.markDataList.filter(item => item.elementType === this.markMode)
              item.elementOrder = currModeMarkData.length
            }
            if (item.elementType === 1) {
              markers[index].style.backgroundColor = 'rgba(0, 0, 0, 0)'
              markers[index].style.border = '2px solid #0f0'
            }
          } else if (item.elementType === 2) {
            if (item.elementOrder === undefined || item.elementOrder === null) {
              const currModeMarkData = this.markDataList.filter(item => item.elementType === this.markMode)
              item.elementOrder = currModeMarkData.length
            }
            markers[index].style.backgroundColor = 'rgba(255, 0, 0, 0.1)'
            markers[index].style.border = '1px dashed #f00'
          }
        }
      });
    },

    onAnnoSelected(e) {
      this.uuid = e.uuid;
      console.log('onAnnoSelected', e)
    },
    onAnnoRemoved(annoData, element) {
      console.log('onAnnoRemoved', annoData, element)
      return true
    },
    onUpdated(e, KEY) {
      console.log("onUpdated", "选框位置或者标框属性发生改动", e, KEY);
      e.forEach(item => {
        item.tranLeft = Number(item.position.x.replace('%', '')) / 100 * document.querySelector('.imgbox').offsetWidth + 'px'
        item.tranTop = Number(item.position.y1.replace('%', '')) / 100 * document.querySelector('.imgbox').offsetHeight + 'px' //限制标注个数超过5个时隐藏select
        item.tag = ''
        item.tagName = ''
      })
      if (!this.markClearing) {
        this.markDataList = e;
      }
      this.markClearing = false
      this.uuid = ''
    },
    //提交
    async toImage() {
      if (!this.checkData()) return
      this.loading = true
      try {
        await this.imgClick(this.imgIndex)
      } finally {
        this.loading = false
      }
    },
    checkData() {
      if (!this.imgList.length) {
        this.$message({
          message: '请先导入图片',
          type: "error",
        });
        return false
      }
      if (!this.imgList.find(item => item.pageOrderType === 1) || !this.imgList.find(item => item.pageOrderType === 2)) {
        this.$message({
          message: '请设置开始节点和结果节点',
          type: "error",
        })
        return false;
      }
      return true;
    },
    async toPreview() {
      if (!this.checkData()) return
      const result = await this.imgClick(this.imgIndex)
      if (!result) return
      await this.$router.push({
        path: "/preview",
        query: {
          questionId: this.imgList[0].questionId,
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.course-config-wrapper {
  border: 1px solid #DCDFE6;
  height: calc(100vh - 40px);
  border-radius: 4px;
  margin: 20px;

  .formList {
    margin-bottom: 15px;

    .nameItem {
      color: rgba(0, 0, 0, 0.9);
      font-size: 14px;
      width: 15%;
      text-align: right;
      margin-right: 10px;
      height: 32px;
      line-height: 32px;
    }

    .bordered {
      width: 80%;
      height: 32px;
      line-height: 32px;
      padding: 0 8px;
      border-radius: 3px;
      border: 1px solid #DCDCDC;
    }

    .picList {
      margin-right: 10px;
      width: 100px;
      position: relative;
      //border: 1px solid #DCDCDC;
      border-radius: 4px;
      cursor: pointer;

      img {
        position: absolute;
        right: -10px;
        bottom: 20px;
        width: 25px;
        height: 25px;
        cursor: pointer;
      }

      .img_name {
        text-align: center;
        text-overflow: ellipsis;
        overflow: hidden;
        white-space: nowrap;
      }
    }

    .picList.selected {
      //border-color: #1296db;
    }
  }

  .left-course-wrapper {
    width: 350px;
    border-right: 1px solid #DCDFE6;
  }

  .topTitle {
    border-bottom: 1px solid #DCDFE6;
    height: 40px;
    line-height: 40px;
    padding-left: 20px;
    color: #303133;

    i {
      display: block;
      height: 40px;
      width: 50px;
      text-align: center;
      line-height: 40px;
    }
  }

  .tabs {
    height: 40px;
    border-bottom: 1px solid #DCDFE6;
    padding-left: 10px;

    div {
      width: 80px;
      line-height: 35px;
      text-align: center;
      border-radius: 4px 4px 0 0;
      font-size: 12px;
      border: 1px solid #DCDFE6;
      border-bottom: none;
      //display: inline-block;
      float: left;
      margin-left: 5px;
      margin-top: 5px;
      height: 35px;
      cursor: pointer;
    }

    div.active {
      background: #EDEEF3;
      color: #666666;
      margin-top: 12px;
      height: 28px;
      line-height: 28px;
    }
  }

  .right_action_wrapper {
    height: calc(100% - 40px);
    display: flex;
    flex-direction: column;
  }

  .course-wrapper-con {
    padding: 10px 20px;
    flex: 1;
    overflow-y: auto;

    .bigBtn {
      width: 100%;
      height: 30px;
      line-height: 30px;
      text-align: center;
      cursor: pointer;
      background: #4080FF;
      color: #ffffff;
      border-radius: 8px;
      font-size: 12px;
    }

    .picBtns {
      display: flex;
      justify-content: space-between;
      margin: 10px 0;

      div {
        font-size: 12px;
        width: 48%;
        height: 30px;
        line-height: 30px;
        text-align: center;
        cursor: pointer;
        background: #ffffff;
        border: 1px solid #4080FF;
        border-radius: 4px;
        color: #4080FF;
      }
    }

    .imgList {
      overflow-y: auto;

      .imgItem {
        height: 160px;
        border: 1px solid #4080FF4D;
        border-radius: 2px;
        margin-bottom: 10px;
        position: relative;

        img {
          width: 100%;
          height: 100px;
        }

        .bottomName {
          font-size: 14px;
          padding: 0 10px;

          .img_name {
            flex: 1;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }

          .optBtn {
            span {
              color: #32C36C;
              margin: 0 10px;
              cursor: pointer;

              img {
                width: 12px;
                height: 12px;
                vertical-align: middle;
                margin-right: 5px;
              }
            }

            span:last-child {
              color: #F88099;
            }
          }
        }

      }

      .imgItem.active {
        border: 2px solid #4080FF;
        box-shadow: 0px 0px 4px 0px #4080FF;

      }

      .upDownBtn {
        position: absolute;
        right: 10px;
        top: 5px;
        width: 25px;

        img {
          width: 25px;
          height: 25px;
          cursor: pointer;
        }

        img.disabled {
          opacity: 0.7;
          cursor: not-allowed
        }
      }
    }

  }

  .smallBtn {
    font-size: 14px;
    width: 90px;
    height: 30px;
    line-height: 30px;
    text-align: center;
    cursor: pointer;
    background: #4080FF;
    border-radius: 15px;
    color: #ffffff;

    img {
      width: 16px;
      vertical-align: middle;
      margin-right: 5px;
    }
  }

  .toolbox_wrapper {
    overflow: hidden;
    transition: height .3s;

    .toolBox {
      padding: 20px;

      .toolItems {
        display: grid;
        grid-template-columns: repeat(2, 1fr);
        grid-row-gap: 15px;
      }

      .toolItems div {
        text-align: center;
        cursor: pointer;

        img {
          width: 60px;
          height: 60px;
        }

        div {
          font-size: 12px;
          color: #303133;
          margin-top: 8px;
        }
      }
    }
  }


  .right-course-wrapper {
    //width: 70%;
    flex: 1;
    height: 100%;
    background: #cccccc;
    position: relative;

    .imgbox {
      //padding: 30px 60px 30px 20px;
      //width: 90%;
      //height: 90%;
    }

    .addMark {
      width: 200px;
      position: absolute;
      //z-index: 99999;
      background: rgba(0, 0, 0, 0.7);
      border-radius: 8px;
      padding: 15px;

      p {
        margin: 15px 0 0 0;
      }
    }

  }
}

.bottom-wrapper {
  border-top: 1px solid #DCDFE6;
  height: 100px;
  padding: 8px 20px;
  border-radius: 4px;
}

.el-upload--picture-card {
  width: 100px !important;
  height: 100px !important;
  line-height: 100px !important;
}

.el-input-number--medium {
  width: 80px !important;
  margin: 0 6px;
}

::v-deep(.resize-dot) {
  border-radius: unset !important;
  border: 2px solid #0c0c0c;
}

::v-deep(.g-image-op) {
  background: #ccc;
}
</style>
